package com.changgou.seckill.listener;

import com.alibaba.fastjson.JSON;
import com.changgou.seckill.service.SeckillOrderService;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.util.Map;

@Component
@RabbitListener(queues = {"${mq.pay.queue.seckillorder}"})
public class SeckillOrderListener {

    @Autowired
    private SeckillOrderService seckillOrderService;

    /**
     * @author 栗子
     * @Description 消费消息
     * @Date 11:54 2019/11/29
     * @param text 监听队列中的消息
     * @return void
     **/
    @RabbitHandler
    public void readMsg(String text) throws ParseException {
        // 消息
        Map<String, String> map = JSON.parseObject(text, Map.class);
        String attach = map.get("attach");
        Map<String, String> attachMap = JSON.parseObject(attach, Map.class);
        String user_id = attachMap.get("username");
        // 处理业务逻辑
        String return_code = map.get("return_code");        // 通信标识

        String out_trade_no = map.get("out_trade_no");
        if ("SUCCESS".equals(return_code)){
            String result_code = map.get("result_code");    // 交易标识
            if ("SUCCESS".equals(result_code)){
                // 支付成功，更新订单

                String transaction_id = map.get("transaction_id");
                String time_end = map.get("time_end");
                seckillOrderService.updateStatus(out_trade_no, user_id, transaction_id, time_end);
            }else {
                // 支付失败，删除订单
                seckillOrderService.deleteOrder(out_trade_no,user_id);
            }
        }
    }
}